package bytebuffer;

import io.Animal;
import io.AnimalHolder;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

public class Main {

   public static void main(String[] args) {
      try {
         new Main();
      } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }
   
   public ByteBuffer byteBuffer;
   
   private ServerSocket serverSocket;
   private Socket userSocket;
   PrintWriter out;
   
   public Main() throws IOException {
      new Decoder();
      /*writeString("tere kool!");
      serverSocket = new ServerSocket(8888);
      listenConnections();*/

   }

   
   private byte[] decode(Object object) {
      Constructor constructor = object.getClass().getDeclaredConstructors()[0];
      Class[] classes = constructor.getParameterTypes();
      long bufferSize = 0;
      return null;
   }
   
   private void writeString(String string) {
      System.out.println("String length > " + string.length());
      byte[] headerBuffer = getAsByteArray(string.length());
      byteBuffer = ByteBuffer.allocate(headerBuffer.length + string.length() + 1);
      byteBuffer.put(headerBuffer);
      byteBuffer.put((byte) 0x0);
      byteBuffer.put(string.getBytes());
      
      System.out.println(">" + byteBuffer.array().length + "<<<");
   }
   
   private byte[] getAsByteArray(long number) {
      int bytesLength = getNumberLengthInBytes(number);
      byte[] header = new byte[bytesLength];
      for (int i = 0; i < bytesLength; i++) {
         int arv2 = 1;
         for (int j = 0; j < i; j++) {
            arv2 *= 256;
         }
         header[bytesLength - i - 1] = (byte) (number / arv2 % 256 - 128);       
      }
      
      System.out.print("Header > ");
      for (byte b : header) {
         System.out.print(" " + (b + 128));
      }
      System.out.println("");
      return header;
   }
   
   private int getNumberLengthInBytes(long number) {
      long a = number;
      int count = 0;
      while (true) {
         count++;
         a >>= 8;
         if (a == 0) break;
      }
      System.out.println("Header length in bytes > " + count);
      return count;
   }
   
   private void listenConnections() throws IOException {     
      while (true) {
         userSocket = serverSocket.accept();
         ObjectOutputStream outputStream = new ObjectOutputStream(userSocket.getOutputStream());
         outputStream.write(byteBuffer.array());
         outputStream.close();
         userSocket.close();
      }
   }

}
